<?php

namespace Mouta\UserBundle\Controller;

use Mouta\AmistateBundle\Entity\SocialNetwork;
use Mouta\UserBundle\Form\Type\MiUbicacionType;
use Mouta\UserBundle\Form\Type\CaracteristicasType;
use Mouta\UserBundle\Form\Type\SobreMiType;
use Mouta\UserBundle\Form\Type\PreferenciasType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\HttpFoundation\Request;

class EditController extends Controller
{
    protected function getDinamicForm()
    {
        /** @var $user \Mouta\AmistateBundle\Entity\Usuario */
        $user = $this->getUser();

        $form = $this->createFormBuilder($user, array('attr' => array('name'=>'SobreMi', 'id'=>'SobreMi')));

        if(!$user->getNombre())
        {
            $form->add('nombre');
            return $form->getForm();
        }

        if(!$user->getCumple())
        {
            $form->add('cumple','birthday', array(
                'format' => 'ddMMyyyy',
                'label'  => 'Cumpleaños',
                'years' => range(date('Y'), date('Y')-70)
            ));
            return $form->getForm();
        }

        if(!$user->getDescripcion())
        {
            $form->add('descripcion','textarea', array(
                'label'  => 'Descríbete',
                'attr' => array('rows' => '6'),
            ));
            return $form->getForm();
        }

        if(!$user->getLat())
        {
            $form->add('pais','hidden')
                ->add('provincia','hidden')
                ->add('localidad','hidden')
                ->add('lat','hidden')
                ->add('lng','hidden')
                ->add('ubicacion','ubicacion', array(
                    'label'  => 'Ubicación',
                    'mapped' => false
                ));
            return $form->getForm();
        }


    }

    public function dinamicFormAction(Request $request)
    {
        $session = $this->get('session');
        $paginasVistas = $session->get('DINAMIC_FORM_CONT',0);
        $paginasVistas++;

        if($request->isMethod('POST') || $paginasVistas > 10)
        {
            $paginasVistas = 0;
            $session->set('DINAMIC_FORM_CONT',$paginasVistas);

            $form = $this->getDinamicForm();
            if(!$form)
            {
                return new Response();
            }

            if ($request->isMethod('POST'))
            {
                $this->procesarForm($form);
            }

            return $this->render('UserBundle:Edit:dinamicForm.html.twig', array(
                'form' => $form->createView(),
            ));


        }
        $session->set('DINAMIC_FORM_CONT',$paginasVistas);

        return new Response();


    }

    public function indexAction()
    {
        $user = $this->getUser();
        $id = $user->getId();
        $em = $this->getDoctrine()->getManager();
        $cant = $em->getRepository('AmistateBundle:Mensaje')->getCountMensajesNoLeidos($id);

        $now = new \DateTime();

        $social = $this->getUser()->getSocial(2);
        if($social && ($now->getTimestamp() - $social->getUpdated()->getTimestamp()) > 43200 ) //medio día
        {
            $data = $user->refreshTwitterPost($this->container->parameters['twitter_api_key'],$this->container->parameters['twitter_api_secret'], $this->container->get('router')->generate('twitter_connect', array(), true));
            if($data)
            {
                $em->persist( $data );
                $em->flush();
            }
        }

        $social = $this->getUser()->getSocial(1);
        if($social && ($now->getTimestamp() - $social->getUpdated()->getTimestamp()) > 43200 ) //medio día
        {
            $data = $user->refreshFacebookPost($this->container->parameters['fos_facebook.app_id'],$this->container->parameters['fos_facebook.secret']);
            if($data)
            {
                $em->persist( $data );
                $em->flush();
            }
        }


        return $this->render('UserBundle:Edit:index.html.twig', array(
            'cant'=>$cant));
    }
	
    public function saveEmailAction()
    {
        $user = $this->getUser();
		$email = $this->getRequest()->get('email');
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('AmistateBundle:Usuario')->findBy(array('email'=>$email));

        $message = null;

		if($users)
		{
			$message = "El Email ya existe";
		}
		
		if(!$email)
		{
			$message = "Ingrese su email";
		}
		
		$emailConstraint = new Email();
        $emailConstraint->message = 'El email es inválido';
		$errorList = $this->get('validator')->validateValue($email, $emailConstraint);
        if (count($errorList) != 0) 
		{
			$message = $errorList[0]->getMessage();
        }
		
		$url = "";
		if(!$message)
		{
			$tokenGenerator = $this->container->get('fos_user.util.token_generator');
			$user->setConfirmationToken($tokenGenerator->generateToken());
			
			$user->setEmail($email);
            $user->setUsername($email);
            $user->setEnabled(false);
			$userManager = $this->container->get('fos_user.user_manager');
            $userManager->updateUser($user);
			
			$mailer = $this->container->get('amistate.user.mailer');
			$mailer->sendConfirmationEmailMessage($user);
			$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());

			$url = $this->container->get('router')->generate('fos_user_registration_check_email');
			
			$this->container->get("security.context")->setToken(null);
			
		}
		
		$response = new Response(json_encode( array('valid'=>($message)?false:true, 'message'=>$message,'url'=>$url) ));
		$response->headers->set('Content-Type', 'application/json');
        return $response;
    }

    public function misDatosAction()
    {
        $user = $this->getUser();
        $sobreMiForm = $this->createForm(new SobreMiType(), $user);
        $miUbicacionForm = $this->createForm(new MiUbicacionType(), $user);
        $caracteristicasForm = $this->createForm(new CaracteristicasType(), $user);
        $preferenciasForm = $this->createForm(new PreferenciasType(), $user);
        $tabToShow = "";


        if ($this->getRequest()->isMethod('POST')) {
            if($this->getRequest()->get('SobreMi'))
            {
                $tabToShow = "sobreMiTab";
                $this->procesarForm($sobreMiForm);
            }
            if($this->getRequest()->get('MiUbicacion'))
            {
                $tabToShow = "ubicacionTab";
                $this->procesarForm($miUbicacionForm);
            }
            if($this->getRequest()->get('Caracteristicas'))
            {
                $tabToShow = "caracteristicasTab";
                $this->procesarForm($caracteristicasForm);
            }
            if($this->getRequest()->get('Preferencias'))
            {
                $tabToShow = "preferenciasTab";
                $this->procesarForm($preferenciasForm);
            }


        }

        return $this->render('UserBundle:Edit:mis_datos.html.twig', array(
            'sobreMiForm' => $sobreMiForm->createView(),
            'miUbicacionForm' => $miUbicacionForm->createView(),
            'caracteristicasForm' => $caracteristicasForm->createView(),
            'preferenciasForm' => $preferenciasForm->createView(),
            'tabToShow' => $tabToShow,
        ));
    }

    protected function procesarForm($form){
        $request = $this->getRequest();

        $form->bind($request);

        if ($form->isValid()) {
            $user = $form->getData();
			$user->setVerificado(false);
            
            $userManager = $this->container->get('fos_user.user_manager');
            $userManager->updateUser($user);

            $this->get('session')->getFlashBag()->add(
                'notice-'.$form->getConfig()->getName(),
                'Sus cambios se guardaron correctamente!'
            );
        }
    }

    public function mostrarAquiAction()
	{
		$user = $this->get('security.context')->getToken()->getUser();
		$message = "";
        if(!$user->getVerificado())
		{
			$message = 'Usted va a aparece aquí cuando un moderador verifique su perfil';
		}
            
		
        $user->setEnHeaderAt( date_create_from_format('d/m/Y', date('d/m/Y')) );
        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();
		$response = new Response(json_encode( array('message'=>$message) ));
		$response->headers->set('Content-Type', 'application/json');
        return $response;
		
    }

    public function twitterConnectAction()
    {
        if($this->getRequest()->get('oauth_token'))
        {
            $storage = new \OAuth\Common\Storage\Session();
            $token = $storage->retrieveAccessToken('Twitter');
            $credentials = new \OAuth\Common\Consumer\Credentials(
                $this->container->parameters['twitter_api_key'],
                $this->container->parameters['twitter_api_secret'],
                $this->container->get('router')->generate('twitter_connect', array(), true)
            );

            $serviceFactory = new \OAuth\ServiceFactory();
            $serviceFactory->setHttpClient(new \OAuth\Common\Http\Client\CurlClient());
            $twitterService = $serviceFactory->createService('twitter', $credentials, $storage);

            $twitterService->requestAccessToken(
                $this->getRequest()->get('oauth_token'),
                $this->getRequest()->get('oauth_verifier'),
                $token->getRequestTokenSecret()
            );

            $user = json_decode($twitterService->request('account/verify_credentials.json'));

            $social = $this->getUser()->getSocial(2);

            if(!$social)
            {
                $social = new SocialNetwork();
            }

            $social->setExternalId($user->id_str);
            $social->setUrl('https://twitter.com/' . $user->screen_name);
            $social->setToken($token->getAccessToken());
            $social->setSecret($token->getAccessTokenSecret());
            $social->setTipo(2);
            $social->setUsuario($this->getUser());
            $em = $this->getDoctrine()->getManager();
            $em->persist($social);
            $em->flush();

            $social = $this->getUser()->refreshTwitterPost( $this->container->parameters['twitter_api_key'], $this->container->parameters['twitter_api_secret'], $this->container->get('router')->generate('twitter_connect', array(), true));

            if($social)
            {
                $em->persist($social);
                $em->flush();
            }

        }

        return $this->redirect($this->generateUrl('user_perfil'), 301);
    }

    public function facebookConnectAction()
    {
        $facebookClient = new \Facebook([
            'appId' => $this->container->parameters['fos_facebook.app_id'],
            'secret' => $this->container->parameters['fos_facebook.secret']
        ]);

        $user = $facebookClient->getUser();
        if(!$user)
        {
            return $facebookClient->getLoginUrl(array('scope' => ['basic_info', 'read_stream'], 'redirect_uri' => $this->container->get('router')->generate('facebook_connect', array(), true)));
        }
        else
        {
            $facebookClient->setExtendedAccessToken();
            $user = $facebookClient->api('/me');

            $social = $this->getUser()->getSocial(1);

            if(!$social)
            {
                $social = new SocialNetwork();
            }

            $social->setExternalId($user['id']);
            $social->setUrl($user['link']);
            $social->setToken($facebookClient->getAccessToken());
            $social->setSecret('');
            $social->setTipo(1);
            $social->setUsuario($this->getUser());
            $em = $this->getDoctrine()->getManager();
            $em->persist($social);
            $em->flush();

            $social = $this->getUser()->refreshFacebookPost( $this->container->parameters['twitter_api_key'], $this->container->parameters['twitter_api_secret']);

            if($social)
            {
                $em->persist($social);
                $em->flush();
            }
        }

        return $this->redirect($this->generateUrl('user_perfil'), 301);
    }
}
